import 'dart:async';

import 'package:flutter/material.dart';
import 'package:sharecommmunit/utils/eventbus.dart';
import 'package:sharecommmunit/utils/http.dart';
import 'package:sharecommmunit/utils/toast.dart';
import 'package:sharecommmunit/utils/token.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  //获得手机号和验证码栏的控制器
  final TextEditingController _phoneController = TextEditingController();
  final TextEditingController _codeController = TextEditingController();
  Timer? _timer;
  
  // 在类的顶部添加一个标志变量
  bool _isSubmitting = false;

  _submit() async {
    
    // 防止重复提交
    if (_isSubmitting) {
      print('正在提交中，请勿重复点击');
      return;
    }
    
    setState(() {
      _isSubmitting = true;
    });
    
    try {
      // print('手机号：${_phoneController.text}');
      // print('验证码：${_codeController.text}');
      //登录时手机号应该不为空且合法
      if (_phoneController.text.isEmpty) {
        ToastUtil.showError('手机号不能为空');
        return;  
      }
      //用正则验证手机号的合法性
      String phone = _phoneController.text;
      RegExp regExp = RegExp(r'^1[3-9]\d{9}$');
      if (!regExp.hasMatch(phone)) {
        ToastUtil.showError('手机号不合法');
        return;
      }
      //用正则验证手机号的合法性 六位数字
      String code = _codeController.text;
      regExp = RegExp(r'^\d{6}$');
      if (!regExp.hasMatch(code)) {
        ToastUtil.showError('验证码不合法');
        return;
      }
      //调用登录接口
      try {
        final res = await http.post('/login',{'mobile': _phoneController.text,'code': _codeController.text});
    
        //存token  
        TokenManager().saveToken(res['data']['token']);
        //关闭定时器
        _timer?.cancel();
        //返回上一页
        Navigator.pop(context);
        //提示登录成功
        ToastUtil.showSuccess('登录成功');
      } catch (e) {
        ToastUtil.showError('登录失败: ${e.toString()}');
      }
       eventBus.fire(RefreshMine());
      // 原有登录逻辑...
    } catch (e) {
      print('登录异常: $e');
      ToastUtil.showError('登录失败: ${e.toString()}');
    } finally {
      setState(() {
        _isSubmitting = false;
      });
    }
  }

  void _getVerificationCode() async {
    //手机号不能为空
    if (_phoneController.text.isEmpty) {
      ToastUtil.showError('手机号不能为空');
      return;
    }
    
    //用正则验证手机号的合法性
    String phone = _phoneController.text;
    RegExp regExp = RegExp(r'^1[3-9]\d{9}$');
    if (!regExp.hasMatch(phone)) {
      ToastUtil.showError('手机号不合法');
      return;
    }
    
    //调用获取验证码接口
    try {
      final res = await http.get(
        '/code',
        params: {'mobile': phone},
      );
      //自动填写填验证码
      if (res != null && res['data'] != null && res['data']['code'] != null) {
        _codeController.text = res['data']['code'];
        //开始倒计时
        _startCountdown();
      } else {
        ToastUtil.showError('获取验证码失败');
      }
    } catch (e) {
      ToastUtil.showError('获取验证码失败: ${e.toString()}');
    }
  }

  int _countdown = 60;
  bool _isCountingDown = false;
  void _startCountdown() {
    if (_isCountingDown) {
      return;
    }
    _isCountingDown = true;
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      setState(() {
        if (_countdown > 0) {
          _countdown--;
        } else {
          _isCountingDown = false;
          _countdown = 60;
          timer.cancel();
        }
      });
    });
  }

  @override
  void deactivate() {
    super.deactivate();
    _timer?.cancel();
  }

  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: const Text('登录'),
        backgroundColor: Colors.transparent,
        centerTitle: true,
      ),
      body: Container(
        padding: const EdgeInsets.all(20),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            const Row(
              children: [
                Text(
                  '登录',
                  style: TextStyle(fontSize: 25, fontWeight: FontWeight.bold),
                ),
              ],
            ),
            const SizedBox(height: 10),
            const Row(
              children: [Text('加入享+, 让生活更轻松', style: TextStyle(fontSize: 15))],
            ),
            const SizedBox(height: 30),
            Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Expanded(
                  child: TextField(
                    controller: _phoneController,
                    decoration: InputDecoration(
                      labelText: '手机号',
                      hintText: '请输入手机号',
                    ),
                  ),
                ),
                ElevatedButton(
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.white,
                    shadowColor: Colors.transparent,
                    foregroundColor: const Color.fromARGB(255, 85, 145, 175),
                    minimumSize: const Size(100, 50),
                  ),
                  onPressed: () {
                    _getVerificationCode();
                  },
                  child:
                      _isCountingDown
                          ? Text(
                            '$_countdown s后重新获取',
                            style: const TextStyle(color: Colors.grey),
                          )
                          : const Text('获取验证码'),
                ),
              ],
            ),
            const SizedBox(height: 8),
            TextField(
              controller: _codeController,
              decoration: InputDecoration(
                labelText: '验证码',
                hintText: '请输入6位验证码',
              ),
            ),
            const SizedBox(height: 8),
            const Row(
              children: [
                Text(
                  '未注册手机号经验证后将自动登录',
                  style: TextStyle(fontSize: 12, color: Colors.grey),
                ),
              ],
            ),
            const SizedBox(height: 50),
            Row(
              children: [
                Expanded(
                  child: ElevatedButton(
                    style: ElevatedButton.styleFrom(
                      backgroundColor: const Color.fromARGB(255, 85, 145, 175),
                      minimumSize: const Size(100, 50),
                    ),
                    onPressed: () {
                      _submit();
                    },
                    child: const Text(
                      '登录',
                      style: TextStyle(color: Colors.white, fontSize: 20),
                    ),
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}
